package de.fuberlin.dbs.wm.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import de.fuberlin.dbs.wm.dao.model.TopTeam;
import de.fuberlin.dbs.wm.dao.model.Tournament;
import de.fuberlin.dbs.wm.dao.util.ResultMapper;
import de.fuberlin.dbs.wm.util.NotAllowedException;

public class TournamentDao extends Dao {
	/**
	 * @param tournament
	 * @return
	 * @throws SQLException 
	 * @throws NotAllowedException 
	 */
	public static List<TopTeam> weAreTheChampions(String tournament) throws SQLException, NotAllowedException {
		if(Dao.hasTournamentReadAccess(tournament)) {
			String sql = "select * from (select Team from table(get_top3('" + tournament + "')) order by spiel desc, tor desc) where rownum < 4 ";
			List<TopTeam> list = db.mapQuery(sql, new ResultMapper<TopTeam>() {
				@Override
				public TopTeam mapResult(ResultSet rs) throws SQLException {
					TopTeam team = new TopTeam(rs.getString("Team"));
					return team;
				}			
			});
			return list;
		}
		else throw new NotAllowedException();
	}
	
	public static List<Tournament> getAll() throws SQLException {
		String sql="select * from turnier order by name ASC";
		List<Tournament> list = db.mapQuery(sql, new ResultMapper<Tournament>() {
			@Override
			public Tournament mapResult(ResultSet rs) throws SQLException {
				if(Dao.hasTournamentReadAccess(rs.getString("Name"))) {
					Tournament tournament = new Tournament(rs.getString("Name"));
					return tournament;
				} else {
					return null;
				}
			}			
		});
		return list;
	}
}
